MainController = $.Controller.extend('main', {
	check : function(response){
		if(response.response == 'NoSession'){
			alert('You have been logged out.  Please log in again to resume.');
			location.href = '/ftp/index?nosession';
			return false;
		}
		return true
	},
	old_selected_id : function(){
			return null;
	},
	set_selected : function(element){
		if(MainController.removed_selected) MainController.removed_selected();
		var style  = element.style;
		style.backgroundColor = 'rgb(49,103,197)';
		style.color = 'white';
		element.selected = true;
		var id = element.id;
		MainController.removed_selected = function(){
			style.backgroundColor = '';
			style.color = '';
			//MainController.old_selected().selected = null;
		};
		MainController.old_selected_id = function(){
			return id;
		};
	},
	stack : [],
	autoload : function(){
		if(MainController.stack.length == 0){
			var next=MVC.$E('/').next().firstDescendant();
			//push each next one to open
			while( next ){
				if(isFolder(next) ){
						MainController.stack.push(next.id);
				}else if(isFile(next)){
					break;
				}
				next = next.next();
			}
		}
		var found = MainController.find_from();
		if(!found) {alert('everything found'); return;}
	
		new MVC.Ajax('/ftp/dir?path='+encodeURIComponent( found.id ), 
		{method: 'post', postBody: '', onComplete: MainController.update } );
		
	},
	find_from : function(){
		var folder =MainController.stack.shift();
		// now try nested folders
		while(folder){
			el = MVC.$E(folder);
			if(needsOpening(el)) return el;
			folder =MainController.stack.shift();
		}
		return null;
	},
	update : function(response){
		
		setTimeout(function(){
			eval('var files = '+response.responseText);
			setTimeout(function(){
				var container = MVC.$E(files.directory).next();
				var sorted = $A(files.files).sort(File.sort);
				new EJS({url: '/templates/files.ejs'}).update(container, {files: sorted, directory: files.directory+'/'} );
				//new FileController().attach_event_handlers(container);
				//new DirectoryController().attach_event_handlers(container);
				container.hide();
				var fd = container.firstDescendant();
				//if(fd)
				//	setTimeout(cont(fd),200)
				//else
				//	setTimeout(MainController.autoload, 200)
				
			},200);
			
			
		},200);
		
	}
},
{
	load : function(params){
        JITS.rightClickMenu.setup_init();
        var completef;
        
        (function(){
            var path;
            MainController.set_upload_path = function(p){
                path = p;
            };
            completef = function(name, size){
                var div = FileView.insert( (path != '/' ? path+ '/' : '') +name);
                div.style.visibility = 'hidden'
                var to = Element.cumulativeOffset(div);
                var i = MainController.fancy_upload.findFile(name, size)
                var el = MainController.fancy_upload.fileList[i].element
                el.innerHTML = name;
                var from = Element.cumulativeOffset(el);
                new Effect.Move(el, {x: (to[0] - from[0]), y: (to[1] - from[1]), mode: 'relative', duration: 0.5,
                    afterFinish: function(){
                        div.style.visibility = '';
                        MainController.fancy_upload.remove(name, size);
                    } 
                })
    	    };
            
        })();
        
        
        
        
        MainController.fancy_upload =  new FancyUpload( MVC.$E('photoupload-filedata-1') , {
			swf: '/swf/Swiff.Uploader.swf',
			queueList: 'photoupload-queue',
			container: MVC.$E('h1'),
			types: {'All Files (*.*)': '*.*'},
			onComplete: completef,
            container: MVC.$E('Upload')
		});
	},
	unload : function(params) {
		if(frames["multipleupload"]) {
			var swiff = frames["multipleupload"].document.getElementById('Swiff1');
			if(swiff)
				swiff.parentNode.removeChild(swiff);
		}
	},
	resize : function(params){
		setTimeout(set_height, 1);
	},
	click : function(params){
		if(MVC.$E('rename')){
	        var name = new MVC.JFile(MVC.$E('rename').parentNode.id).file_and_extension();
			MVC.$E('rename').parentNode.innerHTML = name;
		}
	},
	keypress : function(params){
		if(params.event.ctrlKey && params.event.charCode == 115){
	            alert('call save on edit area');
				stopPropagation(params.event)   ;
	    }
	    if(params.event.charCode == 8 && Range.getWindowRange().isDocumentSelected())
	        stopPropagation(params.event)   ;
	}
});
needsOpening = function(el){
	if(!isFolder(el)) return false;
	var next = el.next();
	return  next.style.display != 'none' && next.innerHTML == '';
};
isFolder = function(el){
	return el.getAttribute('type') ==  'directory';
};
isFile = function(el){
	return el.getAttribute('type') ==  'file';
};
//some continuation that goes through each next step
cont = function(next){
	return function(){
		if(isFolder(next) ){
			MainController.stack.push(next.id);
		}
		next = next.next();
		if(!next || isFile(next)){
			setTimeout(MainController.autoload, 200);
		}else
		{
			setTimeout(cont(next),200 );
		}
	};
};